package com.wolfpire.system.common;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.wolfpire.system.common.util.StringUtils;

public class CommonFunctions {
	


    /**
     * 根据浏览器UA生成下载文件名称（解决乱码问题）
     * @param fileName
     * @param userAgent
     * @return
     */
	public static String buildFileNameByUa(String fileName, String userAgent) {
        try {
            String new_filename = URLEncoder.encode(fileName, "UTF8");
            // 如果没有UA，则默认使用IE的方式进行编码，因为毕竟IE还是占多数的
            String rtn = "filename=\"" + new_filename + "\"";
            if (userAgent!=null && !"".equals(userAgent)) {
                userAgent = userAgent.toLowerCase();
                // IE浏览器，只能采用URLEncoder编码
                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                }
                // Opera浏览器只能采用filename*
                else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
                // Safari浏览器，只能采用ISO编码的中文输�?
                else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                }
                // Chrome浏览器，只能采用MimeUtility编码或ISO编码的中文输�?
                else if (userAgent.indexOf("applewebkit") != -1) {
                    //new_filename = MimeUtility.encodeText(fileName, "UTF8", "B");
                    //rtn = "filename=\"" + new_filename + "\"";
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                }
                // FireFox浏览器，可以使用MimeUtility或filename*或ISO编码的中文输�?
                else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
            return rtn;
        } catch (Exception e) {
            return "";
        }
    }
    
	/**
	 * 根据文件名后缀获取文件类型
	 * @param subfix
	 * @return
	 */
	public static String getContentTypeBySubfix(String subfix) {
		if(subfix!=null && subfix.length()>0) {
			String tmpSubfix = subfix.toLowerCase();
			if(tmpSubfix.equals("doc") || tmpSubfix.equals("docx"))
				return "application/msword";
			else if(tmpSubfix.equals("dms") || tmpSubfix.equals("lha") || tmpSubfix.equals("lzh") || tmpSubfix.equals("exe") || tmpSubfix.equals("class"))
				return "application/octet-stream bin";
			else if(tmpSubfix.equals("pdf"))
				return "application/pdf";
			else if(tmpSubfix.equals("ppt") || tmpSubfix.equals("pptx"))
				return "appication/powerpoint";
			else if(tmpSubfix.equals("zip"))
				return "application/zip";
			else if(tmpSubfix.equals("mpeg") || tmpSubfix.equals("mp2"))
				return "audio/mpeg";
			else if(tmpSubfix.equals("xls") || tmpSubfix.equals("xlsx"))
				return "application/msexcel";
		}
		return "";
	}
	
	/**
	 * 根据类型获取当年的季度列表
	 * @param except 已有的季度列表
	 * @param type 1 排除  2 本身
	 * @return
	 */
	public static List<Map<String, String>> getQuarterListByType(List<String> except, int type) {
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
		Calendar cal = Calendar.getInstance();
		String year = String.valueOf(cal.get(Calendar.YEAR));
		String [] quarters = new String[]{(year+"01"),(year+"02"),(year+"03"),(year+"04")};
		switch(type){
		case 1: //排除
			for(int i=0; i<quarters.length; i++) {
				Map<String, String> quarter = new HashMap<String, String>();
				boolean canAdd = true;
				if(except!=null && except.size()>0) {
					for(int j=0; j<except.size(); j++) {
						if(quarters[i].equals(except.get(j))) canAdd = false;
					}
				}
				if(canAdd) {
					quarter.put("quarter_value", quarters[i]);
					quarter.put("quarter_text", (year+"年第"+(i+1)+"季度"));
					result.add(quarter);
				}
			}
			break;
		case 2: //包含
			if(except!=null && except.size()>0) {
				for(int j=0; j<except.size(); j++) {
					Map<String, String> quarter = new HashMap<String, String>();
					boolean extra = true;
					for(int i=0; i<quarters.length; i++) {
						if(quarters[i].equals(except.get(j))) {
							quarter.put("quarter_value", quarters[i]);
							quarter.put("quarter_text", (year+"年第"+(i+1)+"季度"));
							result.add(quarter);
							extra = false;
						}
					}
					if(extra) {
						String quarterValue = except.get(j);
						quarter.put("quarter_value", quarterValue);
						quarter.put("quarter_text", (quarterValue.substring(0, 4)+"年第"+quarterValue.substring(5)+"季度"));
						result.add(quarter);
					}
				}
			}
			break;
		}
		return result;
	}
	
	/**
	 * 获取季度名称
	 * @param quarter
	 * @return
	 */
	public static String getQuarterText(String quarter) {
		if(quarter==null || quarter.length()!=6) return "";
		String year = quarter.substring(0, 4);
		String count = quarter.substring(5);
		return (year+"年第"+count+"季度");
	}
	
	/**
	 * 获取访问者ip地址
	 * @param request
	 * @return
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		//-- 获取ip地址
	    String ipKey = request.getHeader("X-Real-IP");
	    if (ipKey == null || ipKey.length() == 0 || "unknown".equalsIgnoreCase(ipKey))
	    	ipKey = request.getHeader("X-Forwarded-For");
		if (ipKey == null || ipKey.length() == 0 || "unknown".equalsIgnoreCase(ipKey))
			ipKey = request.getHeader("Proxy-Client-IP");
		else {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ipKey.indexOf(',');
			if (index != -1) {
				ipKey = ipKey.substring(0, index);
			}
		}
		if (ipKey == null || ipKey.length() == 0 || "unknown".equalsIgnoreCase(ipKey))
			ipKey = request.getHeader("WL-Proxy-Client-IP");
		if (ipKey == null || ipKey.length() == 0 || "unknown".equalsIgnoreCase(ipKey))
			ipKey = request.getRemoteAddr();
		return ipKey;
	}
	
	/**
	 * 逗号隔开的数值列表转成List
	 * @param idListStr
	 * @return
	 */
	public static List<Long> idStrToList(String idListStr) {
		List<Long> idList = new ArrayList<Long>();
		if(!StringUtils.isBlank(idListStr)) {
			String [] idArray = idListStr.split(",");
			for(String idStr : idArray) {
				try {
					idList.add(Long.parseLong(idStr));
				} catch (Exception e) { e.printStackTrace(); }
			}
		}
		return idList;
	}
	
	/**
	 * 数值List转成逗号隔开的数值字符串
	 * @param idList
	 * @return
	 */
	public static String idListToStr(List<Long> idList) {
		String idStr = "";
		if(idList!=null && idList.size()>0) {
			for(Long id : idList) {
				idStr += (","+id);
			}
			idStr = idStr.substring(1);
		}
		return idStr;
	}
	
	/**
	 * 计算日期差
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long daysBetween(Date date1, Date date2) {
		if(date1==null || date2==null) return 0L;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date1Tmp = sdf.parse(sdf.format(date1));
			Date date2Tmp = sdf.parse(sdf.format(date2));
			long nd = 1000*24*60*60;//一天的毫秒数
			long date1Time = date1Tmp.getTime();
			long date2Time = date2Tmp.getTime();
			long diff = date1Time - date2Time;
			long days = diff/nd;//计算差多少天
			if(diff%nd>0) days++;
			return days;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0L;
		}
	}
	
	/**
	 * 过滤字符串中的html标签
	 * @param source
	 * @return
	 */
	public static String filterHtml(String source) {
		if(StringUtils.isBlank(source)) return source;
		if(source.indexOf("<")==-1) return source;
		int start = source.indexOf("<");
		int end = source.indexOf(">");
		String result;
		if(end<start) {
			result = source.replaceFirst(">", "");
		} else {
			result = source.substring(0, start)+source.substring(end+1, source.length());
		}
		return filterHtml(result);
	}

}
